const moneyGoalTable = require('../models/moneyGoalTable');
const inspirecloud = require('@byteinspire/inspirecloud-api');
const mgRecordTable = require('../models/mgRecordTable');
const ObjectId = inspirecloud.db.ObjectId;


class MoneyGoalService {
    /**
     * 列出所有攒钱计划
     * @return {Promise<Array<any>>} 返回攒钱计划数组
     */
    async listAll() {
        return await moneyGoalTable.where({is_delete: false}).sort({createAt: -1}).find();
    }

    /**
     * 列出分页内攒钱计划
     */
    async queryPage(params) {
        let {page, limit, user_id} = params;
        let queryParams = {is_delete: false}
        if (user_id !== undefined && user_id.trim() !== '') {
            queryParams.user_id = user_id;
        }
        return await moneyGoalTable.where(queryParams)
            .skip((page - 1) * limit)
            .limit(limit)
            .sort({createAt: -1}).find();
    }

    /**
     * 查询当前已筹金额
     */
    async countCurMoney(mg_id) {
        let queryParams = {is_delete: false, mg_id: mg_id}
        //console.log(queryParams)
        let res = await mgRecordTable.where(queryParams)
            .groupBy().sum('price')
            .as("price")
            .find();
        if (res !== undefined && res.length !== 0) {
            res = res[0].price
        } else {
            res = 0
        }
        return res;

    }


    async getOneById(id) {
        return await moneyGoalTable.where({_id: ObjectId(id)}).findOne();
    }


    /**
     * 创建一条攒钱计划
     * @param moneyGoal 用于创建攒钱计划的数据，原样存进数据库
     * @return {Promise<any>} 返回实际插入数据库的数据，会增加_id，createdAt和updatedAt字段
     */
    async create(moneyGoal) {
        return await moneyGoalTable.save(moneyGoal);
    }

    /**
     * 删除一条攒钱计划
     * @param id 攒钱计划的 _id
     * 若不存在，则抛出 404 错误
     */
    async delete(id) {
        const moneyGoal = await moneyGoalTable.where({_id: ObjectId(id)}).findOne();
        if (!moneyGoal) {
            const error = new Error(`moneyGoal:${id} not found`);
            error.status = 404;
            throw error;
        }
        moneyGoal.is_delete = true;
        await moneyGoalTable.save(moneyGoal);
    }


    /**
     * 更新一条攒钱计划
     * @param newMoneyGoal._id 将会用原对象 merge 此对象进行更新
     * 若不存在，则抛出 404 错误
     */
    async update(newMoneyGoal) {
        const moneyGoal = await moneyGoalTable.where({_id: ObjectId(newMoneyGoal._id)}).findOne();
        if (!moneyGoal) {
            const error = new Error(`moneyGoal:${newMoneyGoal._id} not found`);
            error.status = 404;
            throw error;
        }
        Object.assign(moneyGoal, newMoneyGoal);
        moneyGoal._id = ObjectId(moneyGoal._id)
        await moneyGoalTable.save(moneyGoal);
    }
}

// 导出 Service 的实例
module.exports = new MoneyGoalService();
